package pers.zhouyoudianxi.notice2.view;

import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import pers.zhouyoudianxi.notice2.bean.Notice;
import pers.zhouyoudianxi.notice2.config.DynamicCronTask;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;

import static pers.zhouyoudianxi.notice2.config.DynamicCronTask.NOTICE_LIST;

@Slf4j
public class MainFrame extends JFrame {
    private DynamicCronTask dynamicCronTask = SpringUtil.getBean(DynamicCronTask.class);
    // 表格模型，用于存储和展示配置数据
    private DefaultTableModel tableModel;
    private JTable configTable;
    private SystemTray systemTray;
    private static TrayIcon trayIcon; // 系统托盘图标


    public MainFrame() {
        log.info("初始化主窗体");
        // 设置窗口基本属性
        setTitle("定时提醒小工具");
        setSize(900, 600);
        setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); // 关闭按钮改为隐藏窗口
        setLocationRelativeTo(null); // 居中显示
        setType(Type.UTILITY);

        // 初始化系统托盘
        initSystemTray();

        // 初始化UI组件
        initTable();

        // 加载模拟配置数据
        loadConfigData();

        // 添加双击事件监听器
        addDoubleClickListener();

        // 添加窗口关闭事件监听
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                // 窗口关闭时最小化到系统托盘
                setVisible(false);
                showTrayMessage("定时提醒小工具已最小化", "程序已最小化到系统托盘", TrayIcon.MessageType.INFO);
            }
        });
    }

    /**
     * 初始化系统托盘功能
     */
    private void initSystemTray() {
        // 检查系统是否支持系统托盘
        if (!SystemTray.isSupported()) {
            JOptionPane.showMessageDialog(this, "您的系统不支持系统托盘功能", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        systemTray = SystemTray.getSystemTray();

        // 创建托盘图标（使用简单的自定义图标）
        Image icon = createTrayIcon();
        trayIcon = new TrayIcon(icon, "定时提醒小工具");
        trayIcon.setImageAutoSize(true); // 自动调整图标大小以适应系统托盘

        // 添加双击事件：显示窗口
        trayIcon.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) { // 双击显示窗口
                    setVisible(true);
                    setExtendedState(JFrame.NORMAL); // 从最小化状态恢复
                    toFront(); // 窗口前置
                }
            }
        });

        // 创建右键菜单
        PopupMenu popupMenu = new PopupMenu();
        // 退出程序菜单项
        MenuItem exitItem = new MenuItem("EXIT");
        exitItem.addActionListener(e -> {
            // 从系统托盘移除图标
            systemTray.remove(trayIcon);
            // 退出程序
            System.exit(0);
        });
        popupMenu.add(exitItem);

        // 设置托盘图标的右键菜单
        trayIcon.setPopupMenu(popupMenu);

        // 将图标添加到系统托盘
        try {
            systemTray.add(trayIcon);
        } catch (AWTException e) {
            JOptionPane.showMessageDialog(this, "无法添加图标到系统托盘: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * 创建一个简单的托盘图标
     */
    private Image createTrayIcon() {
        // 创建一个简单的20x20图标
        BufferedImage image = new BufferedImage(20, 20, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();

        // 绘制一个简单的图标（蓝色背景上的白色"C"字母）
        g.setColor(Color.BLACK);
        g.fillRoundRect(0, 0, 20, 20, 5, 5);

        g.setColor(Color.WHITE);
        g.setFont(new Font("Arial", Font.BOLD, 14));
        g.drawString("C", 5, 15);

        g.dispose();
        return image;
    }

    /**
     * 显示托盘消息
     */
    public static void showTrayMessage(String caption, String text, TrayIcon.MessageType messageType) {
        if (trayIcon != null) {
            trayIcon.displayMessage(caption, text, messageType);
        }
    }

    private void initTable() {
        // 创建主面板，使用边界布局
        JPanel mainPanel = new JPanel(new BorderLayout());

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton addButton = new JButton("添加配置");
        addButton.addActionListener(e -> showEditDialog(null));
        buttonPanel.add(addButton);
        mainPanel.add(buttonPanel, BorderLayout.NORTH);

        // 创建表格模型，设置列名（增加状态列）
        String[] columnNames = {"Cron表达式", "标题", "详情", "状态"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            // 设置表格单元格不可编辑
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        // 创建表格并添加到滚动面板
        configTable = new JTable(tableModel);
        // 设置表格列宽
        configTable.getColumnModel().getColumn(0).setPreferredWidth(200);
        configTable.getColumnModel().getColumn(1).setPreferredWidth(150);
        configTable.getColumnModel().getColumn(2).setPreferredWidth(400);
        configTable.getColumnModel().getColumn(3).setPreferredWidth(80);

        // 设置单元格渲染器，用于根据状态改变行颜色
        configTable.setDefaultRenderer(Object.class, new StatusTableCellRenderer());

        JScrollPane scrollPane = new JScrollPane(configTable);
        scrollPane.setBorder(BorderFactory.createTitledBorder("配置列表"));

        // 添加到主面板
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 添加一个状态栏
        JPanel statusPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JLabel statusLabel = new JLabel("已配置数量: " + NOTICE_LIST.size());
        statusPanel.add(statusLabel);
        mainPanel.add(statusPanel, BorderLayout.SOUTH);

        // 将主面板添加到窗口
        add(mainPanel);
    }

    // 自定义单元格渲染器，用于根据状态设置行颜色
    private class StatusTableCellRenderer extends DefaultTableCellRenderer {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                       boolean isSelected, boolean hasFocus,
                                                       int row, int column) {
            Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

            // 获取当前行的状态值
            Notice item = NOTICE_LIST.get(row);
            int status = item.getOpen();

            // 根据状态设置背景颜色（选中状态时保持原有选中样式）
            if (!isSelected) {
                if (status == 1) {
                    c.setBackground(new Color(204, 255, 204)); // 浅绿色 - 关闭
                } else {
                    c.setBackground(new Color(255, 255, 204)); // 浅黄色 - 开启
                }
            }

            return c;
        }
    }

    // 添加双击事件监听器
    private void addDoubleClickListener() {
        configTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                // 检查是否是双击
                if (e.getClickCount() == 2) {
                    int selectedRow = configTable.getSelectedRow();
                    if (selectedRow != -1) {
                        // 获取选中行对应的配置项
                        Notice item = NOTICE_LIST.get(selectedRow);
                        // 显示编辑对话框
                        showEditDialog(item);
                    }
                }
            }
        });
    }

    // 显示编辑对话框
    private void showEditDialog(Notice item) {
        // 创建对话框
        JDialog dialog = new JDialog(this, item == null ? "添加配置" : "修改配置", true);
        dialog.setSize(400, 350);
        dialog.setLocationRelativeTo(this);
        dialog.setLayout(new BorderLayout());
        // 创建输入面板
        JPanel inputPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;

        // Cron表达式输入
        gbc.gridx = 0;
        gbc.gridy = 0;
        inputPanel.add(new JLabel("Cron表达式:"), gbc);

        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JTextField cronField = new JTextField(20);
        inputPanel.add(cronField, gbc);

        // 标题输入
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        inputPanel.add(new JLabel("标题:"), gbc);

        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JTextField titleField = new JTextField(20);
        inputPanel.add(titleField, gbc);

        // 详情输入
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        inputPanel.add(new JLabel("详情:"), gbc);

        gbc.gridx = 1;
        gbc.gridy = 2;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        JTextArea detailArea = new JTextArea(5, 20);
        detailArea.setLineWrap(true);
        inputPanel.add(new JScrollPane(detailArea), gbc);

        // 状态选择（新增）
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        gbc.weighty = 0;
        inputPanel.add(new JLabel("状态:"), gbc);

        gbc.gridx = 1;
        gbc.gridy = 3;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        JComboBox<String> statusCombo = new JComboBox<>(new String[]{"关闭 (0)", "开启 (1)"});
        inputPanel.add(statusCombo, gbc);

        // 如果是修改操作，填充现有数据
        if (item != null) {
            cronField.setText(item.getCron());
            titleField.setText(item.getTitle());
            detailArea.setText(item.getDetail());
            statusCombo.setSelectedIndex(item.getOpen() == 0 ? 0 : 1);
        } else {
            // 新增时默认选择"开启"
            statusCombo.setSelectedIndex(1);
        }

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");

        saveButton.addActionListener(e -> {
            // 验证输入
            String cron = cronField.getText().trim();
            String title = titleField.getText().trim();
            String detail = detailArea.getText().trim();
            int status = statusCombo.getSelectedIndex(); // 0或1

            if (cron.isEmpty() || title.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "Cron表达式和标题不能为空", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (item == null) {
                // 添加新配置项
                Integer id = DynamicCronTask.NEXT_ID + 1;
                Notice newItem = new Notice(id, cron, title, detail, status);
                NOTICE_LIST.add(newItem);
                tableModel.addRow(new Object[]{cron, title, detail, status == 0 ? "关闭" : "开启"});
            } else {
                // 更新现有配置项
                item.setCron(cron);
                item.setTitle(title);
                item.setDetail(detail);
                item.setOpen(status);

                // 更新表格中的数据
                int rowIndex = NOTICE_LIST.indexOf(item);
                if (rowIndex != -1) {
                    tableModel.setValueAt(cron, rowIndex, 0);
                    tableModel.setValueAt(title, rowIndex, 1);
                    tableModel.setValueAt(detail, rowIndex, 2);
                    tableModel.setValueAt(status == 0 ? "关闭" : "开启", rowIndex, 3);
                }
            }
            // 刷新表格以更新颜色
            configTable.repaint();
            dialog.dispose();
            // 更新配置文件
            dynamicCronTask.updateTaskConfig();
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        // 添加面板到对话框
        dialog.add(inputPanel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        // 显示对话框
        dialog.setVisible(true);
    }

    // 加载配置数据
    private void loadConfigData() {
        // 将数据添加到表格模型（不包含ID）
        for (Notice item : NOTICE_LIST) {
            Object[] rowData = {
                    item.getCron(),
                    item.getTitle(),
                    item.getDetail(),
                    item.getOpen() == 0 ? "关闭" : "开启"
            };
            tableModel.addRow(rowData);
        }
    }

    public static void main(String[] args) {
        // 在事件调度线程中启动UI
        SwingUtilities.invokeLater(() -> {
            new MainFrame().setVisible(true);
        });
    }
}
